package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomerException;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.pojo.SetmealDish;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐信息
        this.save(setmealDto);
        //保存菜品对应的套餐信息
        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes();
        setmealDishList.forEach(setmealDish -> setmealDish.setSetmealId(setmealDto.getId()));
        setmealDishService.saveBatch(setmealDishList);
    }

    /**
     * 批量删除
     * @param ids
     */
    @Override
    public void removeWithDish(List<Long> ids) {

        //1.判断套餐是否正在售卖
        QueryWrapper<Setmeal> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.in("id",ids);
        queryWrapper1.eq("status",1);
        int count1 = this.count(queryWrapper1);
        if (count1>0){
            throw new CustomerException("套餐正在售卖,不能删除");
        }
        //1.删除套餐
        this.removeByIds(ids);
        //2.删除套餐菜品数据
        QueryWrapper<SetmealDish> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.in("setmeal_id",ids);
        setmealDishService.remove(queryWrapper2);
    }
}
